package com.pirestupppai.ui.activity;

import android.content.Context;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.SpannableString;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;

import com.pirestupppai.R;
import com.pirestupppai.adapter.CommentListAdapter;
import com.pirestupppai.base.BaseActivity;
import com.pirestupppai.base.BaseAdapter;
import com.pirestupppai.base.BaseStatus;
import com.pirestupppai.bean.Comment;
import com.pirestupppai.bean.LoginUser;
import com.pirestupppai.common.Constant;
import com.pirestupppai.network.NetworkRequest;
import com.pirestupppai.network.TupaiSubscriber;
import com.pirestupppai.utils.FaceConversionUtil;
import com.pirestupppai.utils.Utils;
import com.pirestupppai.widgets.dialog.ConfirmDialog;
import com.pirestupppai.widgets.view.AvatarView;
import com.pirestupppai.widgets.view.FaceRelativeLayout;
import com.pirestupppai.widgets.view.LoadMoreFooter;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * 评论列表
 *
 * @author: xiaoluo
 * @date: 2017-03-13 14:37
 */
public class CommentActivity extends BaseActivity {

    @BindView(R.id.comment_recycler_view)
    RecyclerView recyclerView;
    @BindView(R.id.comment_input_panel)
    EditText inputEt;
    @BindView(R.id.send_comment_btn)
    TextView sendBtn;
    @BindView(R.id.face_layout)
    FaceRelativeLayout faceLayout;
    @BindView(R.id.comment_swipe_layout)
    SwipeRefreshLayout swipeRefreshLayout;

    private LoadMoreFooter mFooterView;
    private View mHeaderView;
    private CommentListAdapter mCommentAdapter;
    private LinearLayoutManager mLinearLayoutManager;

    private int mPosition = 0;  // 列表最后一位
    private int mPage = 1;
    private int mSize = 10;
    private List<Comment> mCommentList = new ArrayList<>();
    private int mTargetId = -1;
    private int mAtPosition = -1;
    private int mAtCommentId = -1;
    private boolean hasMore = true;
    private String mAvatar;
    private String mNickname;
    private String mTime;
    private String mContent;
    private int mUid;

    @Override
    protected Context getActivityContext() {
        return this;
    }

    @Override
    protected int loadParentLayout() {
        return R.layout.activity_comment;
    }

    @Override
    protected void initViews() {
        mTargetId = getIntent().getIntExtra(Constant.IntentKey.TARGET_ID, -1);
        mAvatar = getIntent().getStringExtra(Constant.IntentKey.AVATAR);
        mNickname = getIntent().getStringExtra(Constant.IntentKey.NICKNAME);
        mTime = getIntent().getStringExtra(Constant.IntentKey.TIME);
        mContent = getIntent().getStringExtra(Constant.IntentKey.CONTENT);
        mUid = getIntent().getIntExtra(Constant.IntentKey.UID, -1);

        mFooterView = new LoadMoreFooter(mContext);
        mCommentAdapter = new CommentListAdapter(mContext, mCommentList);
        mCommentAdapter.addFooterView(mFooterView);
        mCommentAdapter.addHeaderView(getHeaderView());
        mLinearLayoutManager = new LinearLayoutManager(mContext);
        mLinearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);

        recyclerView.setLayoutManager(mLinearLayoutManager);
        recyclerView.setAdapter(mCommentAdapter);
        recyclerView.setHasFixedSize(true);
    }

    private View getHeaderView() {
        mHeaderView = LayoutInflater.from(mContext).inflate(R.layout.item_comment_list, null);
        AvatarView avatarView = (AvatarView) mHeaderView.findViewById(R.id.comment_avatar);
        TextView nicknameTv = (TextView) mHeaderView.findViewById(R.id.item_comment_list_name_tv);
        TextView timeTv = (TextView) mHeaderView.findViewById(R.id.comment_time);
        TextView contentTv = (TextView) mHeaderView.findViewById(R.id.item_comment_list_comment_tv);
        View line = (View) mHeaderView.findViewById(R.id.top_line);
        line.setVisibility(View.VISIBLE);

        avatarView.setVisibility(View.GONE);
        nicknameTv.setText(mNickname);
        timeTv.setText(mTime);

        // 将emoji表情转化为icon显示 TODO
        SpannableString spannableString = FaceConversionUtil.getInstace()
                .getExpressionString(mContext,
                        String.valueOf(mContent));
        contentTv.setText(spannableString);
        return mHeaderView;
    }

    @Override
    protected void initListeners() {
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getData(BaseStatus.REFRESH);
            }
        });

        // 监听到达底部事件
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                //到达底部时,加载更多
                int lastVisiblePosition = mLinearLayoutManager.findLastCompletelyVisibleItemPosition() + 1;
                if (mLinearLayoutManager.getChildCount() > 0
                        && mLinearLayoutManager.getItemCount() >= mLinearLayoutManager.getChildCount()
                        && lastVisiblePosition >= mLinearLayoutManager.getItemCount()
                        && dy > 0) {
                    mPosition = lastVisiblePosition;
                    if (hasMore) {
                        mFooterView.setStatus(LoadMoreFooter.Status.LOADING);
                        getData(BaseStatus.LOADMORE);
                    }
                }

                // 防止滑到列表中间时，下拉引起下拉刷新
                if (swipeRefreshLayout.isRefreshing()) {
                    swipeRefreshLayout.setEnabled(true);
                } else {
                    int topRowVewrticalPosition =
                            (recyclerView == null || recyclerView.getChildCount() == 0) ? 0 : recyclerView.getChildAt(0).getTop();
                    swipeRefreshLayout.setEnabled(topRowVewrticalPosition >= 0);
                }
            }
        });

        sendBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendComment();
            }
        });

        mCommentAdapter.setOnItemClickListener(new BaseAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View v, int position) {
                if (mCommentList.get(position).getUser().getId() != LoginUser.getInstance().getId()) {
                    callInputPanel();
                    mAtPosition = position;
                    mAtCommentId = mCommentList.get(position).getId();
                    inputEt.setHint("回复@" + mCommentList.get(position).getUser().getNickname());
                }
            }
        });

        mCommentAdapter.setOnItemLongClickListener(new BaseAdapter.onItemLongClickListener() {
            @Override
            public void onItemLongClick(View v, final int position) {
                if (mCommentList.get(position).getUser().getId() == LoginUser.getInstance().getId()) {
                    final ConfirmDialog dialog = new ConfirmDialog(mContext);
                    dialog.setMessage("确定要删除评论吗?");
                    dialog.setOnSelectListener(new ConfirmDialog.OnSelectListener() {
                        @Override
                        public void onLeftSelect() {

                        }

                        @Override
                        public void onRightSelect() {
                            deleteComment(position);
                        }
                    });
                    dialog.show();
                }
            }
        });

    }

    /**
     * 删除评论
     */
    private void deleteComment(final int position) {
        NetworkRequest.getInstance().deleteComment(mCommentList.get(position).getId(), this,
                new TupaiSubscriber<Comment>(mContext) {
                    @Override
                    protected void requestSuccess(Comment comment) {
                        Utils.showToast("删除成功!");
                        mCommentList.remove(position);
                        mCommentAdapter.notifyDataSetChanged();
                    }

                    @Override
                    protected void requestError(String error) {

                    }
                });
    }

    @Override
    protected void initLogic() {
        // 进入界面就刷新
        swipeRefreshLayout.post(new Runnable() {
            @Override
            public void run() {
                getData(BaseStatus.REFRESH);
                swipeRefreshLayout.setRefreshing(true);
            }
        });
    }

    @Override
    public void onClick(View v) {
    }

    @Override
    public void onBackPressed() {
        if (!faceLayout.hideFaceView() && removeAt()) {
            finish();
        }
    }

    /**
     * 获取数据
     */
    private void getData(final BaseStatus status) {
        if (status == BaseStatus.REFRESH) {
            mFooterView.setStatus(LoadMoreFooter.Status.GONE);
            hasMore = true;
            mPage = 1;
            removeAt();
        } else {
            mPage++;
        }

        NetworkRequest.getInstance().getCommentList(mTargetId, mPage, mSize, this,
                new TupaiSubscriber<List<Comment>>(mContext) {
                    @Override
                    protected void requestSuccess(List<Comment> data) {
                        if (data != null && data.size() != 0) {
                            if (status == BaseStatus.REFRESH) {
                                mCommentList.clear();
                                mCommentList.addAll(data);
                                mCommentAdapter.notifyDataSetChanged();
                            } else {
                                mCommentList.addAll(data);
                                mCommentAdapter.notifyItemInserted(mPosition);
                            }
                        } else {
                            if (status == BaseStatus.REFRESH) {
                                mCommentList.clear();
                                mCommentAdapter.notifyDataSetChanged();
                            }
                            mFooterView.setStatus(LoadMoreFooter.Status.THE_END);
                        }
                        swipeRefreshLayout.setRefreshing(false);

                        if (data != null && data.size() < mSize) {
                            mFooterView.setStatus(LoadMoreFooter.Status.THE_END);
                            hasMore = false;
                        }
                    }

                    @Override
                    protected void requestError(String error) {
                        swipeRefreshLayout.setRefreshing(false);
                        if (status == BaseStatus.LOADMORE) {
                            mFooterView.setStatus(LoadMoreFooter.Status.GONE);
                            mPage--;
                        }
                    }
                });
    }

    /**
     * 移除at
     */
    private boolean removeAt() {
        if (mAtPosition != -1) {
            inputEt.setHint("说点什么吧");
            mAtPosition = -1;
            mAtCommentId = -1;
            return false;
        }
        inputEt.setHint("说点什么吧");
        mAtPosition = -1;
        mAtCommentId = -1;
        return true;
    }

    /**
     * 发送评论
     */
    private void sendComment() {
        if (TextUtils.isEmpty(inputEt.getText().toString())) {
            Utils.showToast("请输入评论");
            return;
        }
        NetworkRequest.getInstance().sendComment(inputEt.getText().toString(), mTargetId, mAtCommentId, this,
                new TupaiSubscriber<Comment>(mContext) {
                    @Override
                    protected void requestSuccess(Comment comment) {
                        inputEt.setText("");
                        hideInputPanel();
                        removeAt();
                        getData(BaseStatus.REFRESH);
                    }

                    @Override
                    protected void requestError(String error) {
                        Utils.showToast("评论失败,请稍后再试");
                    }
                });
    }

    private void hideInputPanel() {
        // 隐藏软键盘
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(sendBtn.getWindowToken(), 0);
    }

    private void callInputPanel() {
        // 唤起输入键盘 并输入框取得焦点
        inputEt.setFocusableInTouchMode(true);
        inputEt.requestFocus();

        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(inputEt, 0);
    }
}
